package com.dm.cloud.utils.mingexcel;

import com.dm.cloud.utils.mingexcel.worker.SheetReader;
import com.dm.cloud.utils.mingexcel.worker.SheetWriter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MingExcelUtil {
    //导出的文件默认名称
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String fileName = sdf.format(new Date());

    //表格导出类
    List<SheetWriter> sheetWriters = new ArrayList<>();

    //表格读入类
    SheetReader sheetReader;

    public static class Builder{
        MingExcelUtil util = new MingExcelUtil();
        public Builder setFileName(String fileName) {
            util.fileName = fileName;
            return this;
        }
        public Builder addSheetWriter(Class<?> clazz, List<?> data) throws IllegalAccessException, InvocationTargetException, InstantiationException {
            util.sheetWriters.add(new SheetWriter(clazz,data));
            return this;
        }
        public Builder setSheetReaderClass(Class<?> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException {
            util.sheetReader = new SheetReader(clazz);
            return this;
        }
        public MingExcelUtil  build(){
            return util;
        }
    }

    /**
     * 导出
     */
    public void exportExcel(HttpServletResponse response) throws IllegalAccessException {
        if(CollectionUtils.isEmpty(sheetWriters)){
            return;
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        if(CollectionUtils.isNotEmpty(sheetWriters)){
            //需要倒着生成 新生成的Sheet会排在前面
            for (int i = sheetWriters.size()-1; i >=0; i--) {
                sheetWriters.get(i).writeSheet(wb);
            }
        }
        try {
            response.setCharacterEncoding("UTF-8");
            // 解决下载文件名中文乱码问题
            String fileNameURL = URLEncoder.encode(fileName+".xlsx", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入
     */
    public List importExcel(MultipartFile multipartFile, int sheetIndex) throws Exception {
        if(null == sheetReader){
            throw new RuntimeException("未设置导入模板类");
        }
        return sheetReader.importExcel(multipartFile,sheetIndex);
    }

}
